#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# -----------------------------------------------------------------------------
# doxyyacc.py
#
#   doxygen-style comment yacc
#
# -----------------------------------------------------------------------------

"""
 supply doxygen-style parsing function
"""

import sys
import yacc
import doxylex

if sys.path[-1]!='..': sys.path.append('..')

from common.debug import *
from common.cglobal import *

# 获取
class elem_list:
    def __init__(self):
        self.cm = []

    def push(self, elem):
        self.cm.append(elem)

    def reset(self):
        del self.cm[:]

doxyl=doxylex.doxylex()      

def doxyyacc(mylexer=doxyl, elist=elem_list()):
    def p_translation_unit(p):
        '''translation_unit : statement
                        | translation_unit statement'''
        pass

    def p_statement_assign(p):
        'statement : KEY expression'
        updatestr(p)
        elist.push([p[1][1:], p[2]])
        if DEBUG_DOXYYACC==1: print(get_cur_info()[0],p[0])
        pass

    def p_statement_line(p):
        'statement : expression'
        if p[1] == '':
            # 如果是空的，可以忽略
            pass
        else:
            # 如果不是空行，应加以保存
            updatestr(p)
            if DEBUG_DOXYYACC==1: print(get_cur_info()[0],p[0])

    def p_expression_com(p):
        'expression : expression WORD NEWLINE'
        #updatestr(p, 1)
        p[0] = ''
        p[0] = p[1] + '\n' + p[2]
        if DEBUG_DOXYYACC==1: print(get_cur_info()[0],p[0])
        pass

    def p_expression_line(p):
        'expression : WORD NEWLINE'
        updatestr(p, 1)
        if DEBUG_DOXYYACC==1: print(get_cur_info()[0],p[0])
        pass

    def p_expression_blankline(p):
        '''expression : BLANKLINE
                       | NEWLINE'''
        p[0] = ''
        if DEBUG_DOXYYACC==1: print(get_cur_info()[0],p[0])

    def p_empty(p):
        'empty : '
        pass

    def p_error(p):
        print("doxy syntax error at '%s L%d'" % (p.value, p.lineno))

    lexer = mylexer.lexer
    tokens = mylexer.tokens
    p1=yacc.yacc(method='LALR', tabmodule='doxy_tab', debugfile='doxyparser.out')
    return p1, elist.cm, lexer

# 打印的格式化字符
FMTSTR='%-12s|  '

if __name__ == '__main__':
    try:
        name = '..\\txt\\doxy.txt'
        if (len(sys.argv) > 1):
            name = sys.argv[1]

        #mylex = doxylex.doxylex()
        #p, elist = doxyyacc(mylex)
        p, elist = doxyyacc()

        f=open(name)
        data = f.read()
        res = p.parse(data,debug=0)
        # 打印输出
        for elem in elist:
            print '-'*50
            print FMTSTR%(elem[0]),
            for line in elem[1].split('\n'):
                print line
                print FMTSTR%(' '),
            print ''

    except EOFError:
        print(e)

